use scraper::{Html, Selector};
use word::{ExampleSentence, Phrase, Pronounce, Word};

pub fn parse(word: String, html: String) -> Result<Word, String> {
    let document = Html::parse_document(&html);
    let basic_selector = Selector::parse(".basic").unwrap();
    let exp_selector = Selector::parse(".word-exp").unwrap();
    return if let Some(basic) = document.select(&basic_selector).next() {
        let mut word = Word::new(word);
        let explains = basic.select(&exp_selector).map(|elem| { elem.text().collect() }).collect();
        word.explains = explains;
        word.pronounce = select_pronounce(&document);
        word.sentences = select_sentences(&document);
        word.phrase = select_phrase(&document);
        Ok(word)
    } else { Err("No match word expression".to_string()) };
}

fn select_pronounce(document: &Html) -> Option<Pronounce> {
    let pronounce_selector = Selector::parse(".phonetic").unwrap();
    let mut pronounce = document.select(&pronounce_selector);
    let mut pr = None;
    if let Some(element) = pronounce.next() {
        pr = Some(Pronounce {
            british: element.text().collect::<String>(),
            american: pronounce.next().unwrap().text().collect::<String>(),
        });
    }
    pr
}


fn select_sentences(document: &Html) -> Vec<ExampleSentence> {
    let sentence_selector = Selector::parse(".catalogue_sentence .trans-container .mcols-layout .col2").unwrap();
    let english_selector = Selector::parse(".sen-eng").unwrap();
    let chinese_selector = Selector::parse(".sen-ch").unwrap();

    let mut sentences: Vec<ExampleSentence> = Vec::with_capacity(3);
    for sentence_container in document.select(&sentence_selector) {
        let en = sentence_container.select(&english_selector).next().unwrap().text().collect();
        let ch = sentence_container.select(&chinese_selector).next().unwrap().text().collect();
        sentences.push(ExampleSentence {
            en,
            ch,
        })
    }
    sentences
}

fn select_phrase(html: &Html) -> Vec<Phrase> {
    let container_selector = Selector::parse(".webPhrase li").unwrap();
    let english_selector = Selector::parse(".point").unwrap();
    let chinese_selector = Selector::parse(".sen-phrase").unwrap();
    let mut phrase: Vec<Phrase> = Vec::new();
    for container in html.select(&container_selector) {
        let en = container.select(&english_selector).next().unwrap().text().collect();
        let ch = container.select(&chinese_selector).next().unwrap().text().collect();
        phrase.push(Phrase { en, ch })
    }
    phrase
}
